package com.california.pay.socket.server;

import com.bwton.socket.log.LoggerUtil;
import com.bwton.socket.transport.URL;
import com.bwton.socket.util.RemotingUtil;
import com.california.pay.common.utils.SpringBeanUtils;
import com.california.pay.service.TerminalLoginService;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class SocketServerIdleHandler extends ChannelDuplexHandler {
    protected static Logger logger = LoggerFactory.getLogger(com.bwton.socket.transport.handler.ServerIdleHandler.class);
    private URL url;
    private TerminalLoginService loginService;

    public SocketServerIdleHandler(URL url) {
        this.url = url;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            try {
                String nettyChannelId = ctx.channel().id().asLongText();
                LoggerUtil.warn(logger, "连接空闲，未发生读和写事件，连接将被关闭，uri: {}", new Object[]{RemotingUtil.parseRemoteAddress(ctx.channel())});

                if (loginService == null){
                    loginService = SpringBeanUtils.getBean(TerminalLoginService.class);
                }
                loginService.logout(ctx.channel(), nettyChannelId);
                ctx.channel().close();
            } catch (Exception e) {
                LoggerUtil.error(logger, "[SocketServerIdleHandler#userEventTriggered]关闭连接时产生异常!", e);
            }

            super.userEventTriggered(ctx, evt);
        }

    }
}
